import json
import tornado.ioloop
import tornado.options
from tornado.websocket import WebSocketHandler
from tornado.web import Application
import pymongo

from listener import Listener


class Receiver(WebSocketHandler):
    db = pymongo.MongoClient().test.test

    def open(self):
        self.application.connection.register(self.callback)
        print("WebSocket opened")

    def on_close(self):
        self.application.connection.unregister(self.callback)
        print("WebSocket closed")

    def callback(self, msg):
        self.write_message(msg)

    def on_message(self, message):
        """receive task result from probe, json
        """
        pass


class Connection(object):
    callbacks = []

    def register(self, callback):
        self.callbacks.append(callback)

    def unregister(self, callback):
        self.callbacks.remove(callback)

    def notifyCallbacks(self, msg):
        for callback in self.callbacks:
            callback(msg)

    def new_task(self, msg):
        """new task from web page
        """
        pass


class App(Application):
    def __init__(self):
        self.connection = Connection()
        Listener(self.connection.new_task)

        handlers=[(r'/websocket', Receiver)]

        tornado.web.Application.__init__(self, handlers)


if __name__ == "__main__":
    app = App()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8080)
    tornado.ioloop.IOLoop.instance().start()
